package com.tieshan.smartwindow.widget

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.widget.ImageView
import android.widget.LinearLayout
import com.bumptech.glide.Glide
import com.tieshan.smartwindow.R
import timber.log.Timber
import java.util.ArrayList

/**
 * author : Hleo
 * time   : 2022-2-12
 * desc   : 箭头指向动画
 */
class AnimationView_Left @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    var aa: AlphaAnimation = AlphaAnimation(0f, 1f)
    var index = 0 //图片角标
    var imagedatas: MutableList<ImageView> = ArrayList()
    var number=6
    var imgSize=30f
    init {
        val a = context.theme.obtainStyledAttributes(attrs, R.styleable.AnimationView, 0, 0)
         number = a.getInteger(R.styleable.AnimationView_number,6)
         imgSize = a.getDimension(R.styleable.AnimationView_imgSize,30f)
        initView(context)
    }

    private fun initView(context: Context) {
        for (i in 0..number) {
            val imageView = ImageView(context)
            Glide.with(context).load(R.mipmap.ic_left).into(imageView)
            addView(imageView)
            val layoutParams = imageView.layoutParams as LayoutParams
            layoutParams.width = imgSize.toInt()
            layoutParams.height = imgSize.toInt()
            imageView.layoutParams = layoutParams
            imageView.visibility = INVISIBLE
            imagedatas.add(imageView)
        }
        index=imagedatas.size-1
        startAnimation(imagedatas)
        orientation = HORIZONTAL
        gravity = Gravity.CENTER
    }

    private fun startAnimation(imagedatas: List<ImageView>) {
        imagedatas[index].visibility = VISIBLE
        aa.duration = 300
        try {
            aa.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation) {}
                override fun onAnimationEnd(animation: Animation) {
                    imagedatas[index].post {
                        index--
                        if (index == -1) {
                            index = imagedatas.size-1
                            for (i in imagedatas.indices) {
                                imagedatas[i].visibility = INVISIBLE
                            }
                        }
                        imagedatas[index].visibility = VISIBLE
                        imagedatas[index].startAnimation(animation)
                    }
                }

                override fun onAnimationRepeat(animation: Animation) {}
            })
            imagedatas[index].startAnimation(aa)
        }catch (e:Exception){
            Timber.e(e.toString())
        }

    }

    fun setNumbers(number:Int){
        this.number=number;
        invalidate()
    }


}